package cn.edu.hqu.cst.android.ljc.sharedpreferences;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static int MODE = MODE_PRIVATE;//设置为被本应用读写
    public static final String PREFERENCE_NAME = "SaveSetting";//存储数据的文件名
    Button btnLogin;
    EditText etAccount,etPassword;
    SharedPreferences sharedPreferences;
    String account,password;
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);
        intent = new Intent(MainActivity.this, SucceedActivity.class);

        etAccount = findViewById(R.id.account_input);
        etPassword = findViewById(R.id.password_input);

        //设置保存的文件名和模式
        sharedPreferences = getSharedPreferences(PREFERENCE_NAME,MODE);

        account = sharedPreferences.getString("account",null);//第二个参数为设置默认值，设为null
        password = sharedPreferences.getString("password",null);//第二个参数为设置默认值，设为null

        etAccount.setText(account);
        etPassword.setText(password);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_login) {
            if (account != null && password != null) {//如果已经保存过数据
                if (account.equals(etAccount.getText().toString()) && password.equals(etPassword.getText().toString())){
                    startActivity(intent);
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(MainActivity.this, "账户或密码错误", Toast.LENGTH_SHORT).show();
                }//判断输入的账号密码是否为空
            } else if (!etAccount.getText().toString().isEmpty() && !etPassword.getText().toString().isEmpty()){//EditText的转为字符串后默认返回值是""而不是null
                account = etAccount.getText().toString();//获取输入的账号
                password = etPassword.getText().toString();//获取输入的密码
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("account", account);//保存账号
                edit.putString("password", password);//保存密码
                edit.apply();//提交数据
                startActivity(intent);
                Toast.makeText(MainActivity.this, "已保存账号和密码", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "账号或密码不能为空", Toast.LENGTH_SHORT).show();
            }
        }
    }
}